import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'

//封装一个判断当前模块是否有权限的方法
function hasUrl(url: any, next: any) {
  //首先要判断当前要请求的地址在不在数组中，如果在就next不在就跳首页
  let result = store.getters.getUser.menus_url.some((item: any) => url === item)
  if (result) {
    next()
  } else {
    next("/home")
  }
}

export const IndexRoutes = [
  {
    path: "/home",
    component: () => import("../views/home.vue"),
  },

  {
    path: "/menu",
    component: () => import("../views/menu/menu.vue"),
    name: "菜单管理",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/menu", next)
    }
  },
  {
    path: "/role",
    component: () => import("../views/role/role.vue"),
    name: "角色管理",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/role", next)
    }


  },
  {
    path: "/user",
    component: () => import("../views/user/user.vue"),
    name: "管理员管理",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/user", next)
    }
  },
  {
    path: "/cate",
    component: () => import("../views/cate/cate.vue"),
    name: "商品分类",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/cate", next)
    }
  },
  {
    path: "/specs",
    component: () => import("../views/specs/specs.vue"),
    name: "商品规格管理",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/specs", next)
    }
  },
  {
    path: "/manage",
    component: () => import("../views/goods/goods.vue"),
    name: "商品详情管理",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/manage", next)
    }
  },
  {
    path: "/member",
    component: () => import("../views/member/member.vue"),
    name: "会员列表",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/member", next)
    }
  },
  {
    path: "/banner",
    component: () => import("../views/banner/banner.vue"),
    name: "轮播图管理",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/banner", next)
    }
  },
  {
    path: "/seck",
    component: () => import("../views/seck/seck.vue"),
    name: "活动列表",
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/seck", next)
    }
  },

]

const routes: Array<RouteRecordRaw> = [



  {
    path: "/index",
    component: () => import("@/pages/index.vue"),
    children: [
      ...IndexRoutes,
      {
        path: "",
        redirect: "/home"
      },

    ]
  },
  {
    path: "/login",
    component: () => import("../pages/login.vue"),

  },
  {
    path: "/:pathMatch(.*)",
    redirect: "/index"

  },



]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
//封装全局登录事件 使用全局路由守卫
router.beforeEach((to: any, from: any, next: any) => {
  //1.首先判断用户访问的地址是否登录
  if (to.path == '/login') {
    next() //放行
    return
  }
  if (store.getters.getUser) {
    next()
    return
  }
  //3，如果仓库没有值得的话就强制跳转登录同页面
  next('/login')
})

export default router
